package com.codingfly.controller.common;

import com.codingfly.core.exception.BizException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

public class BaseController {

    /**
     * 参数的非空校验
     * @param object
     * @param requiredFields
     */
    public void checkParams(Object object, List<String> requiredFields) {
        if (ObjectUtils.isEmpty(requiredFields)) {
            throw new BizException("required fields not allow null");
        }
        checkParams(object, requiredFields.toArray(new String[]{}));
    }

    /**
     * 参数的非空校验
     * @param object
     * @param requiredFields
     */
    public void checkParams(Object object, String... requiredFields) {
        if (requiredFields == null || requiredFields.length < 1) {
            throw new BizException("required fields not allow null");
        }

        if (object instanceof Map) { // 校验map的非空参数
            Map paramsMap = (Map) object;
            Arrays.stream(requiredFields).forEach(arg -> {
                if (!paramsMap.containsKey(arg)) {
                    throw new BizException("缺少参数" + arg);
                } else if (ObjectUtils.isEmpty(paramsMap.get(arg))) {
                    throw new BizException(arg + "不允许为空");
                }
            });
        } else { // 校验DTO的非空参数
            Class clazz = object.getClass();
            for (String fieldName : requiredFields) {
                Field field = ReflectionUtils.findField(clazz, fieldName);
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, object);
                if (value == null || value.toString().length()<1) {
                    throw new BizException(fieldName + "不允许为空");
                } else if (value instanceof Object[]) {
                    Object[] arr = (Object[]) value;
                    if (arr.length == 0) {
                        throw new BizException(fieldName + "不允许为空");
                    }
                } else if (value instanceof List) {
                    List list = (List)value;
                    if (list.size()<1) {
                        throw new BizException(fieldName + "不允许为空");
                    }
                } else if (value instanceof Set) {
                    Set set = (Set)value;
                    if (set.size()<1) {
                        throw new BizException(fieldName + "不允许为空");
                    }
                }
            }
        }
    }

}